package 链表;

/**
 * @author 陈建军
 * https://leetcode-cn.com/problems/reverse-linked-list-ii/
 */
public class _92_反转链表II {
    /**
     * 简单的原理，定义三个指针
     *      一个指向从反转开始的第一个位置的前方 prev
     *      一个指向当前的节点，来进行反转
     *      一个指向当前节点的下一个节点
     * 先让curr.next指向next.next
     * 再将curr.next提出来，就是将curr.next指向prev.next 再将prev.next指向于next
     * 循环次数为right - left
     * 之后循环即可
     * @param head 目标节点
     * @param left 左
     * @param right 右
     * @return ListNode
     */
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (head == null || head.next == null || left == right) {
            return head;
        }
        ListNode dummyNode = new ListNode(0, head);
        ListNode prev = dummyNode;
        for (int i = 1; i < left; i++) {
            prev = prev.next;
        }
        ListNode curr = prev.next;
        ListNode next;
        int sum = right - left;
        for (int i = 0; i < sum; i++) {
            next = curr.next;
            curr.next = next.next;
            next.next = prev.next;
            prev.next = next;
        }
        return dummyNode.next;
    }
}
